package com.yjf.ljr.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yjf.ljr.R;
import com.yjf.ljr.application.MyApplication;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.dataclass.EasyDataClass;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.service.LockPatternService;
import com.yjf.ljr.util.LockPatternUtils;
import com.yjf.ljr.util.SPreferences;

public class LockPatternSettingActivity extends IjActivity implements View.OnClickListener {

	public static final int FIRST_INIT_LOCK_PATTERN = 1;
	public static final int FORGET_LOCK_PATTERN = 2;
	public static final int NON_SETTING_PATTERN = 3;
	public static final String IS_CHANGE_LOCK_PATTERN = "is_change_lock_pattern";
	public static final String LOCK_PATTERN_IS_OPEN = "lock_pattern_is_open";

	@ID("lock_pattern_switch")
	private CheckBox lockPatternSwitch;
	@ID("lock_pattern_setting")
	private RelativeLayout lockPatternSetting;
	@ID("lock_pattern_switch_container")
	private RelativeLayout lockPatternSwitchContainer;
	@ID("lockpattern_setting")
	private TextView lockPatternSettingTv;
	@ID("lock_pattern_forget")
	private RelativeLayout lockPatternForget;

	private String lastUserName;

	private MyApplication myApplication;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lock_pattern_setting);
		myApplication = (MyApplication) getApplication();
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();
		refreshView();
		// if(!CommonData.IS_LOGIN) {
		// loginWebview();
		// }
	}

	private void initView() {
		setTitleStr(getString(R.string.lockpattern));
		setLeftBtnClick();
		lockPatternSetting.setOnClickListener(this);
		lockPatternSwitchContainer.setOnClickListener(this);
		lockPatternForget.setOnClickListener(this);
	}

	private void checkBoxCheckChange(boolean isChecked) {
		LockPatternUtils lockPatternUtils = new LockPatternUtils(LockPatternSettingActivity.this);
		if (isChecked && !lockPatternUtils.isPatternEverChosen()) {
			Intent intent = new Intent(LockPatternSettingActivity.this, LockPatternActivity.class);
			startActivityForResult(intent, FIRST_INIT_LOCK_PATTERN);
		} else {
			updateLockPatternSwitch(isChecked);
			if (isChecked) {
				// 开启自动登陆
				myApplication.startAutoLogin();
			} else {
				// 关闭自动登陆
				myApplication.stopAutoLogin();
			}

			SPreferences.saveData(LockPatternSettingActivity.this, isChecked, CommonData.USER_NAME
					+ LOCK_PATTERN_IS_OPEN);
		}
	}

	private void refreshView() {
		boolean isOpen = (Boolean) SPreferences.getData(this, false, CommonData.USER_NAME + LOCK_PATTERN_IS_OPEN);
		updateLockPatternSwitch(isOpen);
	}

	private void updateLockPatternSwitch(boolean isChecked) {
		if (isChecked) {
			lockPatternSwitch.setBackgroundResource(R.drawable.password_on);
		} else {
			lockPatternSwitch.setBackgroundResource(R.drawable.password_off);
		}
		LockPatternUtils lockPatternUtils = new LockPatternUtils(LockPatternSettingActivity.this);
		lockPatternSetting.setVisibility(isChecked ? View.VISIBLE : View.GONE);
		lockPatternForget.setVisibility(isChecked ? View.VISIBLE : View.GONE);
		if (!lockPatternUtils.isPatternEverChosen()) {
			lockPatternSettingTv.setText(R.string.lockpattern_create);
			lockPatternSetting.setVisibility(View.VISIBLE);
		} else {
			lockPatternSettingTv.setText(R.string.lockpattern_setting);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if (resultCode == RESULT_OK) {
			if (requestCode == FIRST_INIT_LOCK_PATTERN) {
				lockPatternSwitch.setChecked(true);
				updateLockPatternSwitch(lockPatternSwitch.isChecked());
				if (lockPatternSwitch.isChecked()) {
					// 开启自动登陆
					myApplication.startAutoLogin();
				} else {
					// 关闭自动登陆
					myApplication.stopAutoLogin();
				}
				SPreferences.saveData(LockPatternSettingActivity.this, lockPatternSwitch.isChecked(),
						CommonData.USER_NAME + LOCK_PATTERN_IS_OPEN);
			} else if (requestCode == FORGET_LOCK_PATTERN) {
				if (!TextUtils.isEmpty(lastUserName) && lastUserName.endsWith(CommonData.USER_NAME)) {
					LockPatternUtils lockPatternUtils = new LockPatternUtils(this);
					lockPatternUtils.deleteLockPattern();
					Intent newIntent = new Intent(LockPatternSettingActivity.this, LockPatternActivity.class);
					newIntent.putExtra(LoginActivity/* WvLoginActivity */.FIRST_LOGIN, true);
					startActivityForResult(newIntent, NON_SETTING_PATTERN);
				}
			} else if (requestCode == NON_SETTING_PATTERN) {
				refreshView();
			}
		}
	}

	@Override
	public void onClick(View v) {

		if (!CommonData.IS_LOGIN) {
			Toast.makeText(LockPatternSettingActivity.this, "请登录后再操作！", Toast.LENGTH_SHORT).show();
			return;
		}

		switch (v.getId()) {
		// 设置密码
		case R.id.lock_pattern_setting:
			Intent intent = new Intent(LockPatternSettingActivity.this, LockPatternActivity.class);
			intent.putExtra(IS_CHANGE_LOCK_PATTERN, true);
			LockPatternUtils lockPatternUtils1 = new LockPatternUtils(LockPatternSettingActivity.this);
			if (!lockPatternUtils1.isPatternEverChosen()) {
				startActivityForResult(intent, FIRST_INIT_LOCK_PATTERN);
			} else {
				startActivity(intent);
			}
			break;
		// 手势密码开关
		case R.id.lock_pattern_switch_container:
			boolean isOpen = (Boolean) SPreferences.getData(this, false, CommonData.USER_NAME + LOCK_PATTERN_IS_OPEN);
			lockPatternSwitch.setChecked(!isOpen);
			checkBoxCheckChange(!isOpen);
			break;
		// 忘记密码
		case R.id.lock_pattern_forget:
			LockPatternUtils lockPatternUtils = new LockPatternUtils(LockPatternSettingActivity.this);
			if (!lockPatternUtils.isPatternEverChosen()) {
				showToast("您当前未设置手势密码！");
			} else {
				forgetLockPattern();
			}
			break;
		default:
			break;
		}

	}

	private void forgetLockPattern() {
		new AlertDialog.Builder(this).setTitle("提示").setIcon(R.drawable.icon_exit)
				.setMessage("\n  忘记手势密码需要通过登录来重新设置。\n").setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						lastUserName = CommonData.USER_NAME;
						CommonData.SESSIONID = "";
						// 退出登陆，需将用户名清空
						CommonData.IS_LOGIN = false;
						MyAccountActivity.gIsLoginServer = false;
						// CommonData.USER_NAME = "";
						// 关闭自动登陆
						myApplication.stopAutoLogin();
						SPreferences.clearPassword(LockPatternSettingActivity.this);

						// CookieManager cookieManager =
						// CookieManager.getInstance();
						// cookieManager.removeSessionCookie();
						// CookieSyncManager.getInstance().sync();

						Intent intent = new Intent();
						// intent.setClass(LockPatternSettingActivity.this,
						// WvLoginActivity.class);
						// intent.putExtra("advUrl", CommonData.LOGIN_URL);
						// intent.putExtra("advTitle", "登录");
						// intent.putExtra("registration", "注册");
						intent.setClass(LockPatternSettingActivity.this, LoginActivity.class);
						startActivityForResult(intent, FORGET_LOCK_PATTERN);
					}
				}).setNegativeButton("取消", null).show();
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		// TODO Auto-generated method stub
		return false;
	}
}
